<?php

include_once MODELS.'combustivel.php';
include_once ENTITIES.'combustivel.php';

class CombustivelController {
    
    private $modelCombustivel;
    
    public function __construct() {
        $this->modelCombustivel = new CombustivelModel();
    }
    
    public function addCombustivel(Combustivel $combustivel = null){
        if($combustivel == null){
            $combustivel = new Combustivel();
            $this->linkCombustivel($combustivel);
        }
        $vars = get_object_vars($combustivel);
        unset($vars['id']);
        foreach ($vars as $v) { 
            if(empty($v) && $v != '0') return false; 
        }
        return $this->modelCombustivel->insert($combustivel);
    }
    
    public function linkCombustivel(Combustivel &$combustivel){
        $config = Config::getInstance();
        $combustivel->litros    = (int) $config->filter('litros');
        $combustivel->preco     = (float) str_replace(',', '.', $config->filter('preco'));
        $combustivel->kmInicial = (int) $config->filter('km-inicial');
        $combustivel->kmFinal   = (int) $config->filter('km-final');
        $combustivel->despesa   = $config->filter('despesa');
    }
    
    public function removeCombustivel($combustivel){
        return $this->modelCombustivel->delete($combustivel);
    }
    
    public function removeCombustivelFromDespesa($despesa){
        $combustivel = $this->getCombustivelByDespesa($despesa);
        return $this->modelCombustivel->delete($combustivel->id);
    }
    
    public function getCombustivel($id_combustivel){
        $condition  = CombustivelModel::ID.'='.$id_combustivel;
        $res        = $this->modelCombustivel->select('*', $condition);
        if(empty($res)) return new Combustivel();
        return $res[0];
    }
    
    public function getCombustivelByDespesa($despesa){
        $condition  = CombustivelModel::DESPESA.'='.$despesa;
        $res        = $this->modelCombustivel->select('*', $condition);
        if(empty($res)) return new Combustivel();
        return $res[0];
    }
    
    public function getAllCombustivels(){
        return $this->modelCombustivel->select();
    }
    
}
?>
